﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Com.JunCaiSoft.Common.Controller;
using Com.JunCaiSoft.Common.Enums;
using Com.JunCaiSoft.Common.ExchangeData;
using Com.JunCaiSoft.Permission.Entity;
using Com.JunCaiSoft.Permission.IDao;
using Com.JunCaiSoft.Permission.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Com.JunCaiSoft.API.Permission.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class RoleController : BaseController<Role,Role,Role,Guid>
    {
        public RoleController(IRoleDao roledao) : base(roledao)
        {

        }
        /// <summary>
        /// 按用户ID批量删除
        /// </summary>
        /// <param name="Id">用户ID列表</param>
        /// <returns></returns>
        [HttpPatch]
        public virtual async Task<ActionResult> DeleteList(IEnumerable<Guid> Id)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                int result = DaoAsync.DeleteListAsync<Role>(x => Id.Contains(x.Id)).Result;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ListByPageAsync(int pageIndex, int pageSize,string keyword)
        {
            try
            {
                QueryData<Role> result = new QueryData<Role>();

                if (keyword != null && keyword != "")
                {
                    result = await DaoAsync.ListByPageAsync(x => x.Name.Contains(keyword), x => x.CreateTime, pageIndex, pageSize, OrderbyType.desc);
                }
                else
                {
                    result = await DaoAsync.ListByPageAsync(x => x.CreateTime, pageIndex, pageSize, OrderbyType.desc);
                }

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 获取权限树
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> GetAllAuthorizes()
        {
            return await Task.Run(() => Content(JsonConvert.SerializeObject(APIConfig.GetAuthorizes())));
        }
    }
}
